﻿using System;
using System.Data.SqlClient;
using System.Text;
using HPortal.Lib;
using System.IO;
using System.Text.RegularExpressions;

namespace OsPortal.oAppCore.Core.ImageUpload
{
    public partial class uImg : System.Web.UI.Page
    {
        public string Filepath = System.Configuration.ConfigurationManager.AppSettings["OsPortal.PortalCore.FckUserFiles"].ToString();
        public string WebPath = System.Configuration.ConfigurationManager.AppSettings["OsPortal.PortalCore.WebPathUserFiles"].ToString();
        public void SaveResource(ref string path, string filename, byte[] content, string ext)
        {
            string IoFilepath = this.Server.MapPath(Filepath);
            DateTime dt = DateTime.Now;
            string directory = string.Format("{0}/{1}", IoFilepath, dt.ToString("yyMM/dd"));
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            string file = string.Format("/{0}{1}{2}", dt.ToString("HHmmss"), filename, ext);
            File.WriteAllBytes(string.Format("{0}{1}", directory, file), content);
            path = string.Format("{0}/{1}{2}{3}", WebPath, dt.ToString("yyMM/dd/HHmmss"), filename, ext);
        }
        public void GetExtResource(string contentType, out string ext, out string type)
        {
            ext = string.Empty;
            type = string.Empty;
            switch (contentType)
            {
                case "image/jpeg":
                case "image/pjpeg":
                    ext = ".jpg";
                    type = "img";
                    break;
                case "image/gif":
                    ext = ".gif";
                    type = "img";
                    break;
                case "image/bmp":
                    ext = ".bmp";
                    type = "img";
                    break;
                case "image/png":
                case "image/x-png":
                    ext = ".png";
                    type = "img";
                    break;
            }
        }
        protected void UploadButton_Click(object sender, EventArgs e)
        {
            try
            {
                string script = string.Empty;
                if (this.imgupload.PostedFile != null)
                {
                    string ext;
                    string type;
                    string contentType = this.imgupload.PostedFile.ContentType;
                    this.GetExtResource(contentType, out ext, out type);
                    if (type != "img")
                    {
                        HtmlHelper.Alert("Co loi: Dinh dang file \"" + contentType + "\", vui long chon file dinh dang jpg,gif,bmp hoac png.", this.Page);
                        return;
                    }
                    else
                    {
                        byte[] content = new byte[this.imgupload.PostedFile.ContentLength];
                        this.imgupload.PostedFile.InputStream.Read(content, 0, content.Length);
                        int length = content.Length;

                        if (this.chkSaveForWeb.Checked)
                        {
                            byte[] contTmp_ = ImageHelper.GetThumbnail(System.Drawing.Image.FromStream(this.imgupload.PostedFile.InputStream), 90L, -1, -1);
                            if (contTmp_.Length < length)
                            {
                                content = contTmp_;
                                length = contTmp_.Length;
                            }
                            contentType = "image/jpeg";
                        }
                        int ImgSize_MaxKB = HtmlHelper.GetIntFromRequestString("ms", 0);
                        if (ImgSize_MaxKB != 0)
                        {
                            int imgSize = length / 1024;
                            if (imgSize > ImgSize_MaxKB)
                            {
                                this.RunScript(string.Format("Ok(-1,'{0}');", imgSize));
                                return;
                            }
                        }
                        string webImgPath = string.Empty;

                        Match match = Regex.Match(this.imgupload.PostedFile.FileName, @"(?:.*/|.*\\)*(?<FullName>(?<Name>[^.]+).(?:[^?$]+))$");
                        string filename = match.Groups["Name"].Value;
                        this.SaveResource(ref webImgPath, filename, content, ext);
                        script = string.Format("Ok('1','{0}');dialog.CloseDialog();", webImgPath);
                    }
                }
                else
                    script = "Ok(0,'');";
                this.RunScript(script);
            }
            catch (Exception ex)
            {
                HtmlHelper.Alert(ex.Message, this.Page);
            }
        }
        private void RunScript(string script)
        {
            this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "UploadImage", string.Format(@"<script type='text/javascript'>{0}</script>", script));
        }
    }
}
